package middleware

import (
	"net/http"
	"strings"

	"backend-api/pkg/utils"

	"github.com/gin-gonic/gin"
)

// FrontendAuthMiddleware 前台用户认证中间件
func FrontendAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取Authorization头
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "缺少认证令牌",
				"data":    nil,
			})
			c.Abort()
			return
		}

		// 检查Bearer前缀
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "认证令牌格式错误",
				"data":    nil,
			})
			c.Abort()
			return
		}

		// 解析JWT令牌
		claims, err := utils.ParseFrontendToken(parts[1])
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "认证令牌无效: " + err.Error(),
				"data":    nil,
			})
			c.Abort()
			return
		}

		// 将用户信息存储到上下文中
		c.Set("user_id", claims.UserID)
		c.Set("user_uuid", claims.UUID)
		c.Set("username", claims.Username)
		c.Set("user_type", claims.UserType)

		c.Next()
	}
}

// AdminAuthMiddleware 后台管理员认证中间件
func AdminAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取Authorization头
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "缺少认证令牌",
				"data":    nil,
			})
			c.Abort()
			return
		}

		// 检查Bearer前缀
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "认证令牌格式错误",
				"data":    nil,
			})
			c.Abort()
			return
		}

		// 解析JWT令牌
		claims, err := utils.ParseAdminToken(parts[1])
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "认证令牌无效: " + err.Error(),
				"data":    nil,
			})
			c.Abort()
			return
		}

		// 将管理员信息存储到上下文中
		c.Set("admin_id", claims.UserID)
		c.Set("admin_uuid", claims.UUID)
		c.Set("admin_username", claims.Username)
		c.Set("user_type", claims.UserType)

		c.Next()
	}
}

// GetCurrentUserID 从上下文中获取当前用户ID
func GetCurrentUserID(c *gin.Context) (uint, bool) {
	userID, exists := c.Get("user_id")
	if !exists {
		return 0, false
	}
	if id, ok := userID.(uint); ok {
		return id, true
	}
	return 0, false
}

// GetCurrentUserUUID 从上下文中获取当前用户UUID
func GetCurrentUserUUID(c *gin.Context) (string, bool) {
	userUUID, exists := c.Get("user_uuid")
	if !exists {
		return "", false
	}
	if uuid, ok := userUUID.(string); ok {
		return uuid, true
	}
	return "", false
}

// GetCurrentAdminID 从上下文中获取当前管理员ID
func GetCurrentAdminID(c *gin.Context) (uint, bool) {
	adminID, exists := c.Get("admin_id")
	if !exists {
		return 0, false
	}
	if id, ok := adminID.(uint); ok {
		return id, true
	}
	return 0, false
}

// GetCurrentAdminUUID 从上下文中获取当前管理员UUID
func GetCurrentAdminUUID(c *gin.Context) (string, bool) {
	adminUUID, exists := c.Get("admin_uuid")
	if !exists {
		return "", false
	}
	if uuid, ok := adminUUID.(string); ok {
		return uuid, true
	}
	return "", false
}